<?php
use EasyWeChat\Factory;

class Weixin {

	private $config;

    public function __construct($config)
    {
		$this->config = [
			'app_id' => $config['app_id'],
			'secret' => $config['app_secret'],
			'response_type' => 'array',
			'log' => [
				'level' => 'debug',
				// 'file' => __DIR__.'/wechat.log',
			],
		];

        $this->wxapp = Factory::miniProgram($this->config);
        
	}

	public function login($code){
		$session = $this->wxapp->auth->session($code);
		// $openid = $session['openid'];
		return $session;
	}

	public function checkText($content){
		$result = $this->wxapp->content_security->checkText($content);
		return $result;
	}

	public function getTel($code,$iv,$encryptedData){
		$session = $this->wxapp->auth->session($code);
		$session_key = $session['session_key'];

		$decryptedData  = $this->wxapp->encryptor->decryptData($session_key, $iv, $encryptedData);
		if($decryptedData['phoneNumber']){
			return $decryptedData['phoneNumber'];
		}
		return false;
	}

	public function getQrcode($data){
		$response = $this->wxapp->app_code->getUnlimit($data['scene'], [
			'page'  => $data['page'],
			'width' => $data['width'],
		]);
		if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
			$fileurl = $response->saveAs('./upload/qrcode', $data['filename']);
		}
		return $fileurl;
    }

    //微信支付
	public function payment($config,$order){
		$config = [
			// 必要配置
			'app_id'             => $config['app_id'],
			'mch_id'             => $config['mch_id'],
			'key'                => $config['mch_key'],   // API 密钥
		
			// 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
			'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
			'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
		
			'notify_url'         => '默认的订单回调地址',     // 你也可以在下单时单独设置来想覆盖它
		];
        
		$payment = Factory::payment($config);
		$jssdk = $payment->jssdk;
		// dump($jssdk);exit;
		// $result = $jssdk->bridgeConfig($prepayId, false);

		$attributes = [
			'trade_type' => 'JSAPI',              // 支付方式，小程序支付使用JSAPI
			'body' => $order['msg'],            // 订单说明
			'out_trade_no' => $order['payno'],  // 自定义订单号
			'total_fee' => $order['money'] * 100,               // 单位：分
			'openid' => $order['openid']                  // 当前用户的openId
		];
	 
		$result = $payment->order->unify($attributes);
		// dump($result );exit;
		if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
			$prepayId = $result['prepay_id'];
			// $config = $jssdk->sdkConfig($prepayId);
			$bridgeConfig = $jssdk->bridgeConfig($prepayId, false);
			return $bridgeConfig;
		}
	
		return false;
    }


	// shop
	public function sessionKey($code)
    {
        /**
         * code 换取 session_key
         * ​这是一个 HTTPS 接口，开发者服务器使用登录凭证 code 获取 session_key 和 openid。
         * 其中 session_key 是对用户数据进行加密签名的密钥。为了自身应用安全，session_key 不应该在网络上传输。
         */
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $result = json_decode(curl($url, [
            'appid' => $this->appId,
            'secret' => $this->appSecret,
            'grant_type' => 'authorization_code',
            'js_code' => $code
        ]), true);
        if (isset($result['errcode'])) {
            $this->error = $result['errmsg'];
            return false;
        }
        return $result;
	}
	

	 /**
     * 数组转json
     * @param $data
     * @return string
     */
    protected function jsonEncode($data)
    {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    /**
     * json转数组
     * @param $json
     * @return mixed
     */
    protected function jsonDecode($json)
    {
        return json_decode($json, true);
    }

    /**
     * 返回错误信息
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }

}